package com.sz.youban.dt.service.allinpay;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sz.youban.dt.entity.allinpay.DtPayNotifyRecords;
import com.sz.youban.dt.entity.allinpay.DtPayRecords;
import com.sz.youban.dt.entity.pay.PayNotifyStatus;
import com.sz.youban.dt.entity.pay.PayStatus;
import com.sz.youban.dt.interfs.allinpay.IDtPayNotifyRecordsService;
import com.sz.youban.dt.model.PairDef;
import com.sz.youban.dt.service.allinpay.mapper.DtPayNotifyRecordsMapper;
import com.sz.youban.dt.service.allinpay.mapper.DtPayRecordsMapper;
import com.sz.youban.dt.service.allinpay.helpper.AllinpayUtil;
import com.sz.youban.dt.service.utils.GO;
import com.sz.youban.tonglian.entity.common.TongLianPayMsg;
import com.sz.youban.tonglian.entity.common.TongLianPayResultCode;
import com.sz.youban.tonglian.entity.common.TongLianPaySysParam;
import com.sz.youban.tonglian.service.TranxServiceImpl;
import com.sz.youban.tonglian.service.TranxServiceInstance;

/**
 * <p>
 * 支付结果回调记录 服务实现类
 * </p>
 *
 * @author ruichar
 * @since 2017-06-15
 */
@Service
public class DtPayNotifyRecordsServiceImpl extends ServiceImpl<DtPayNotifyRecordsMapper, DtPayNotifyRecords> implements IDtPayNotifyRecordsService {

    private final Logger logger = LoggerFactory.getLogger(DtPayNotifyRecordsServiceImpl.class);
    @Autowired
    private DtPayRecordsMapper payRecordsMapper;

    @Autowired
    private DtPayNotifyRecordsMapper payNotifyRecordsMapper;

    @Value("${develop}")
    private Boolean develop;

    //通联查询交易
    private TranxServiceImpl tranxService = TranxServiceInstance.newInstance();

    /*
     * 1.扫描交易中的支付记录
     * 2.查询通联
     * 3.根据通联返回的情况更改交易记录
     * 4.更改的交易记录存入待通知表
     *
     */
    @Override
    public void scanPayRecords() {


        DtPayRecords payRecordsParam = new DtPayRecords();
        payRecordsParam.setStatus(PayStatus.DEAL_ING.getStatus());
        List<DtPayRecords> payRecordsList = payRecordsMapper.selectPayRecordsByParam(payRecordsParam);
        Date now = new Date();
        if (null != payRecordsList && !payRecordsList.isEmpty()) {
            for (DtPayRecords item : payRecordsList) {
                //通联访问与查询交易状态
//				PairDef<Integer, String> tongLianPair = tongLianReturnStatus(item,tranxService,item.getType());
                PairDef<Integer, TongLianPayMsg> tongLianPair = tongLianReturnStatus(item, tranxService, item.getType());
                if (PayStatus.DEAL_ING.getStatus() != tongLianPair.getFirst()) {
                    item.setTsp(now);
                    item.setStatus(tongLianPair.getFirst());
                    if (null == tongLianPair.getSecond().getResultMsg()) 
                    {
                        item.setDesc("");
                    }
                    else
                    {
                    	item.setDesc(tongLianPair.getSecond().getResultMsg());
                    }
                    if (!StringUtils.isEmpty(tongLianPair.getSecond().getSettleDay())) {
                        item.setSettleDay(tongLianPair.getSecond().getSettleDay());
                    }

                    payRecordsMapper.updatePayRecordsStatus(item);
                    DtPayNotifyRecords addNotifyItem = new DtPayNotifyRecords();
                    addNotifyItem.setDealNo(item.getDealNo());
                    addNotifyItem.setAmount(item.getAmount());  //此处金额是从pay_records取来，因此不做金额转换
                    addNotifyItem.setOrderNo(item.getOrderNo());
                    addNotifyItem.setStatus(PayNotifyStatus.NOTIFY_NO.getStatus());//未通知
                    addNotifyItem.setSubTime(item.getSubTime());
                    addNotifyItem.setTsp(now);
                    payNotifyRecordsMapper.insert(addNotifyItem);
                }
            }
        }
    }


    /**
     * @param item
     * @param txcode :交易类型（代收，代付）
     * @return 通联查询得到的最终交易状态//待完成
     * status:交易状态条件, 0成功,1失败, 2全部,3退票,4代付失败退款,5代付退票退款,6委托扣款7提现
     * selectCode:200004 交易结果的查询交易代码
     */
    private PairDef<Integer, TongLianPayMsg> tongLianReturnStatus(DtPayRecords item, TranxServiceImpl tranxService, Integer txcode) {
        PairDef<Integer, TongLianPayMsg> result = new PairDef<>();
        int resultStatus = PayStatus.DEAL_ING.getStatus();
        try {
        	String selectCode = "200004";//
        	int status = 2;//
            TongLianPaySysParam paySysParam = AllinpayUtil.getTongLianSystemObj(develop, txcode + "");
            TongLianPayMsg tongLianMsg = tranxService.queryTradeNewByDealNo(selectCode,status,item.getDealNo(), false, paySysParam);
            if (TongLianPayResultCode.DEAL_ERROR == tongLianMsg.getResultCode()) {
                resultStatus = PayStatus.DEAL_ERROR.getStatus();
//				result.setSecond(tongLianMsg.getResultMsg());
                result.setSecond(tongLianMsg);
            } else if (TongLianPayResultCode.DEAL_SUCCESS == tongLianMsg.getResultCode()) {
                resultStatus = PayStatus.DEAL_SUCC.getStatus();
//				result.setSecond(tongLianMsg.getResultMsg());
                result.setSecond(tongLianMsg);
            }
        } catch (Exception e) {
            logger.error("=================e:{}", e);
        }
        result.setFirst(resultStatus);
        return result;
    }

}
